(function () {
  // 图片懒加载
  function lazyload(images = []) {
    var clientHeight = document.documentElement.clientHeight;
    var lastIndex = 0;
    return function () {
      var item;
      var scrollTop = document.documentElement.scrollTop;
      scrollTop = scrollTop || document.body.scrollTop;
      for (var i = lastIndex, l = images.length; i < l; i++) {
        item = images[i];
        // 如果图片距离浏览器窗口顶部的高度 <= 窗口的高度 + 已经滚动的高度
        // 证明图片已经出现在可视区域中了
        if (item.offsetTop <= clientHeight + scrollTop) {
          item.src = item.getAttribute("data-src");
          item.removeAttribute("data-src");
          lastIndex++;
        }
      }
    };
  }

  // 节流: 一段时间内, 只会触发一次
  function throttle(fn, times = 1000) {
    var timer;
    var $this = this;
    var args = arguments;
    return function () {
      if (timer) return;
      timer = setTimeout(() => {
        fn.apply($this, args);
        timer = null;
      }, times);
    };
  }

  var init = function () {
    var images = document.querySelectorAll("#app img");
    window.onload = window.onscroll = throttle(lazyload(images), 500);
  };

  init();
})();
